package rpt

import (
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/rpt"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/advertising"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/app-starter/persistence"
	"github.com/lishimeng/go-log"
)

func createScheduleRpt(clientId string, name, startDate, endDate string, template rpt.Template) (report db.AmazonRpt, err error) {

	err = app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		report.ClientId = clientId
		report.Name = name
		report.AmazonRptDuration.StartDate = startDate
		report.AmazonRptDuration.EndDate = endDate

		report.TableChangeInfo.Status = db.RptStatusInit
		report.RptTemplateId = template.GetTplName()
		report.Desc = "schedule"
		_, e = tx.Context.Insert(&report)
		return
	})
	if err != nil {
		log.Info("save rpt fail")
		log.Info(err)
		return
	}
	log.Info("save rpt success")
	return
}

func updateRptStatus(_ string, rpt advertising.RptStatus) {
	var err error
	err = app.GetOrm().Transaction(func(tx persistence.TxContext) (e error) {
		var tmp db.AmazonRpt
		e = tx.Context.QueryTable(new(db.AmazonRpt)).
			Filter("RptId", rpt.ReportId).
			One(&tmp)
		if e != nil {
			log.Info("update rpt fail")
			log.Info(e)
			return
		}
		log.Info("update rpt status")
		tmp.RptState = rpt.Status
		tmp.RptUpdateAt = rpt.UpdatedAt

		tmp.AmazonRptFile.RptFileUrl = rpt.Url
		tmp.AmazonRptFile.RptFileSize = rpt.FileSize
		tmp.AmazonRptFile.RptFileExpireAt = rpt.UrlExpiresAt

		tmp.RptFailureReason = rpt.FailureReason
		if tmp.RptState == "COMPLETED" {
			tmp.Status = db.RptStatusGenCompleted
		} else if tmp.RptState == "FAILED" {
			tmp.Status = db.RptStatusFail
		} else if tmp.RptState == "PROCESSING" {
			tmp.Status = db.RptStatusProcessing
		}
		_, e = tx.Context.Update(&tmp)
		return
	})
	if err != nil {
		log.Info("update rpt fail")
		log.Info(err)
		return
	}
	log.Info("update rpt status success")
}
